package unimelb.filesync.server.protocol;

import java.security.KeyPair;

import unimelb.filesync.common.crypto.CryptoUtils;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class CreateKeyPairPhase implements IFileSyncPhase {

    private final ProtocolContext context;

    private final CryptoUtils cryptoUtils;

    public CreateKeyPairPhase(ProtocolContext context) {
        super();
        this.context = context;
        this.cryptoUtils = new CryptoUtils();
    }

    @Override
    public void execute() {
        final String keyFileName = context.getObject(ProtocolContext.SERVER_KEY_FILE);

        KeyPair rsaKeyPair = null;
        if (cryptoUtils.isRsaKeyFilesExist(keyFileName)) {
            System.out.println("Key pair already exists. Reading from file");
            rsaKeyPair = cryptoUtils.readRsaKeyPair(keyFileName);
        } else {
            System.out.println("Key pair does not exist. Generating");
            rsaKeyPair = cryptoUtils.createRsaKeyPair((Integer) context.getObject(ProtocolContext.SERVER_KEY_SIZE));
            cryptoUtils.saveRsaKeyPair(rsaKeyPair, keyFileName);
        }

        context.addObject(ProtocolContext.SERVER_KEY_PAIR, rsaKeyPair);
    }

}
